﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class MoveComp : MonoBehaviour, IDragHandler, IEndDragHandler, IBeginDragHandler
{
    public System.Action<Vector2> m_OnMove;
    public Vector2 m_Delta;
    [SerializeField] float m_Radius = 30;
    [SerializeField] RectTransform m_Indicator;
    Vector2 m_LastPosition;
    [SerializeField] bool m_IsRight;
    float m_DelayTime = 0.2f; 

    public void OnDrag(PointerEventData eventData)
    {
        // Debug.LogError(m_Delta);
        if (m_IsRight)
        {
            m_Delta = (eventData.position - m_LastPosition).normalized;

            if (Vector2.Distance(eventData.position, m_LastPosition) <= 0.1f)
            {
                m_Delta = Vector2.zero;
            }
            m_LastPosition = eventData.position;

            if (m_OnMove != null)
            {
                m_OnMove(m_Delta);
            }
        }
        else
        {
            m_Delta = (eventData.position - m_LastPosition).normalized;
            if (m_Indicator != null)
            {
                m_Indicator.anchoredPosition = m_Delta * m_Radius;
            }
            if (m_OnMove != null)
            {
                m_OnMove(m_Delta);
            }
        }
    }

    void Update()
    {
        if (m_IsRight)
        {
            Invoke("Stop", m_DelayTime);
        }
    }

    void Stop()
    {
        m_Delta = Vector2.zero;
        if (m_OnMove != null)
        {
            m_OnMove(m_Delta);
        }
    }

    private void OnDestroy()
    {
        m_OnMove = null;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        m_LastPosition = eventData.position;
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        m_LastPosition = Vector2.zero;
        if (m_Indicator != null)
        {
            m_Indicator.anchoredPosition = Vector2.zero;
        }
        m_Delta = Vector2.zero;
    }
}
